package cn.zkc.library.biz;

import cn.zkc.library.modal.Ticket;
import cn.zkc.library.modal.User;
import cn.zkc.library.modal.exceptions.LoginRegisterException;
import cn.zkc.library.service.TicketService;
import cn.zkc.library.service.UserService;
import cn.zkc.library.utils.ConCurrentUtils;
import cn.zkc.library.utils.MD5;
import cn.zkc.library.utils.TicketUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.LobRetrievalFailureException;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author kay
 * @version 1.0
 * @date 2020/6/27 18:01
 * @description
 */

@Service
public class LoginBiz {

    @Autowired
    private UserService userService;

    @Autowired
    private TicketService ticketService;

    public String login(String email,String password){
        User user = userService.getUser(email);
        if(null == user)
            throw new LoginRegisterException("邮箱不存在");
        if(!StringUtils.equals(MD5.next(password), user.getPassword()))
            throw new LoginRegisterException("密码不正确");

        Ticket t = ticketService.getTicket(user.getId());

        if(t == null){
            t = TicketUtils.next(user.getId());
            ticketService.addTicket(t);
            System.out.println(t);
            return t.getTicket();
        }

        if(t.getExpiredAt().before(new Date())) {
            ticketService.deleteTicket(t.getId());
        }

        t = TicketUtils.next(user.getId());
        ConCurrentUtils.setHost(user);
        return t.getTicket();
    }

}
